package com.xc.utils.stock.sina;

import com.google.common.collect.Lists;
import com.xc.common.ServerResponse;
import com.xc.pojo.Stock;
import com.xc.utils.HttpClientRequest;
import com.xc.utils.PropertiesUtil;
import com.xc.utils.redis.JsonUtil;
import com.xc.utils.stock.sina.vo.SinaStockMinData;
import com.xc.vo.stock.StockListVO;
import com.xc.vo.stock.StockVO;
import com.xc.vo.stock.k.MinDataVO;
import com.xc.vo.stock.k.echarts.EchartsDataVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import org.codehaus.jackson.type.TypeReference;

import javax.management.StringValueExp;

/**
 *
 * @author xiongcan
 * @version 1.0
 * @date 2018/9/28 下午8:21
 */
@Slf4j
public class SinaStockApi {

    //  http://hq.sinajs.cn/list=sh601318

    public static final String sina_url
            = PropertiesUtil.getProperty("sina.single.stock.url");

    /**
     *  获取新浪的股票行情 str
     * @param stockGid
     * @return
     */
    public static String getSinaStock(String stockGid){
        String sina_result = "";
        try {
            sina_result = HttpClientRequest.doGet(sina_url + stockGid);
        }catch (Exception e){
            log.error("获取股票行情出错，错误信息 = {}",e);
        }
        String hqstr = sina_result.substring(sina_result.indexOf("=") + 2);
//        log.info("行情data = {}",hqstr);
        return hqstr;
    }


    public static StockListVO assembleStockListVO(String sinaResult){
        StockListVO stockListVO = new StockListVO();

        String[] hqarr = sinaResult.split(",");

        //  名称
        stockListVO.setName(hqarr[0]);

        // 现价
        stockListVO.setNowPrice(hqarr[3]);

//        log.info("股票 {} 现价 = {} 昨收 = {}" , hqarr[0] , hqarr[3] , hqarr[2]);

        //涨跌幅 （如果停牌，分母为0，涨幅为0）
        BigDecimal chang_rate = new BigDecimal("0");
        if(new BigDecimal(hqarr[2]).compareTo(new BigDecimal("0")) != 0){
            //  (hqarr[3]-hqarr[2]) / hqarr[2] * 100
            chang_rate = new BigDecimal(hqarr[3])
                    .subtract(new BigDecimal(hqarr[2]));
            chang_rate = chang_rate.multiply(new BigDecimal("100"))
                    .divide(new BigDecimal(hqarr[2]),2, RoundingMode.HALF_UP);
        }
        stockListVO.setHcrate(chang_rate);

        //  当日最高
        stockListVO.setToday_max(hqarr[4]);
        //  当日最低
        stockListVO.setToday_min(hqarr[5]);

        //  成交额
        stockListVO.setBusiness_amount(hqarr[8]);

        //  成交量
        stockListVO.setBusiness_balance(hqarr[9]);

        //  昨收
        stockListVO.setPreclose_px(hqarr[2]);

        //  今开
        stockListVO.setOpen_px(hqarr[1]);

        return stockListVO;
    }
    public static StockVO assembleStockVO(String sinaResult){
        StockVO stockVO = new StockVO();

        String[] hqarr = sinaResult.split(",");

        //  名称
        stockVO.setName(hqarr[0]);

        // 现价
        stockVO.setNowPrice(hqarr[3]);

//        log.info("股票 {} 现价 = {} 昨收 = {}" , hqarr[0] , hqarr[3] , hqarr[2]);

        //涨跌幅 （如果停牌，分母为0，涨幅为0）
        BigDecimal chang_rate = new BigDecimal("0");
        if(new BigDecimal(hqarr[2]).compareTo(new BigDecimal("0")) != 0){
            //  (hqarr[3]-hqarr[2]) / hqarr[2] * 100
            chang_rate = new BigDecimal(hqarr[3])
                    .subtract(new BigDecimal(hqarr[2]));
            chang_rate = chang_rate.multiply(new BigDecimal("100"))
                    .divide(new BigDecimal(hqarr[2]),2, RoundingMode.HALF_UP);
        }
        stockVO.setHcrate(chang_rate);

        //  当日最高
        stockVO.setToday_max(hqarr[4]);
        //  当日最低
        stockVO.setToday_min(hqarr[5]);

        //  成交额
        stockVO.setBusiness_amount(hqarr[8]);

        //  成交量
        stockVO.setBusiness_balance(hqarr[9]);

        //  昨收
        stockVO.setPreclose_px(hqarr[2]);

        //  今开
        stockVO.setOpen_px(hqarr[1]);

        //  五档买卖
        stockVO.setBuy1(hqarr[6]);
        stockVO.setBuy2(hqarr[13]);
        stockVO.setBuy3(hqarr[15]);
        stockVO.setBuy4(hqarr[17]);
        stockVO.setBuy5(hqarr[19]);

        stockVO.setSell1(hqarr[7]);
        stockVO.setSell2(hqarr[23]);
        stockVO.setSell3(hqarr[25]);
        stockVO.setSell4(hqarr[27]);
        stockVO.setSell5(hqarr[29]);

        stockVO.setBuy1_num(hqarr[10]);
        stockVO.setBuy2_num(hqarr[12]);
        stockVO.setBuy3_num(hqarr[14]);
        stockVO.setBuy4_num(hqarr[16]);
        stockVO.setBuy5_num(hqarr[18]);

        stockVO.setSell1_num(hqarr[20]);
        stockVO.setSell2_num(hqarr[22]);
        stockVO.setSell3_num(hqarr[24]);
        stockVO.setSell4_num(hqarr[26]);
        stockVO.setSell5_num(hqarr[28]);

        //  图


        return stockVO;
    }


    /**
     *  获取股票 分钟 图 K 线
     *  http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=sz000001&scale=5&ma=5&datalen=1023
     * @param stock
     * @param time
     * @param ma
     * @param size
     * @return
     */
    public static ServerResponse<MinDataVO> getStockMinK(Stock stock, int time, int ma, int size){
        //  最大长度 240
        int maxSize = Integer.parseInt(PropertiesUtil.getProperty("sina.k.min.max.size"));
        if(size > maxSize){
            size = maxSize;
        }

        String minUrl = PropertiesUtil.getProperty("sina.k.min.url");
        minUrl = minUrl + "?symbol="+ stock.getStockGid() +"&scale="+ time +"&ma="+ ma +"&datalen=" + size;

        String hqstr = "";
        try {
            hqstr = HttpClientRequest.doGet(minUrl);
        }catch (Exception e){
            log.error("获取股票K线分时图出错，错误信息 = {}" ,e);
        }

        log.info(" time = {} ma = {} size = {}" ,time,ma,size);

//        log.info("股票K线分时图(未转换) data = {}",hqstr);

        hqstr = hqstr.replace("day", "\"day\"")
                .replace("open", "\"open\"")
                .replace("high", "\"high\"")
                .replace("low", "\"low\"")
                .replace("close", "\"close\"")
                ;
        if(ma == 5){
            hqstr = hqstr.replace("ma_volume5", "\"ma_volume\"")
                    .replace(",volume", ",\"volume\"")
                    .replace("ma_price5", "\"ma_price\"");
        }else if(ma == 10){
            hqstr = hqstr.replace("ma_volume10", "\"ma_volume\"")
                    .replace(",volume", ",\"volume\"")
                    .replace("ma_price10", "\"ma_price\"");
        }else if(ma == 15){
            hqstr = hqstr.replace("ma_volume15", "\"ma_volume\"")
                    .replace(",volume", ",\"volume\"")
                    .replace("ma_price15", "\"ma_price\"");
        }else{
            return ServerResponse.createByErrorMsg("ma 取值 5，10，15");
        }
//        log.info("股票K线分时图(已转换) data = {}",hqstr);

        if(StringUtils.isBlank(hqstr)){
            return ServerResponse.createByErrorMsg("没有查询到行情数据");
        }

        MinDataVO minDataVO = new MinDataVO();
        minDataVO.setStockName(stock.getStockName());
        minDataVO.setStockCode(stock.getStockCode());
        minDataVO.setGid(stock.getStockGid());

        List<SinaStockMinData> list = JsonUtil.string2Obj(hqstr
                ,  new TypeReference<List<SinaStockMinData>>() {} );
//        log.info("成功，转换成 SinaStockMinData list");

        log.info("需要查询的行情size为： {}" , size);
//        log.info("查询到 SinaStockMinData list 为： {}" , list.size());
        minDataVO.setData(list);

        return ServerResponse.createBySuccess(minDataVO);
    }

    /**
     *      minDataVO To echartsDataVO
     *      转换成 echarts 需要的数据格式
      */
    public static EchartsDataVO assembleEchartsDataVO(MinDataVO minDataVO){
        EchartsDataVO echartsDataVO = new EchartsDataVO();
        echartsDataVO.setStockName(minDataVO.getStockName());
        echartsDataVO.setStockCode(minDataVO.getStockCode());

        List<SinaStockMinData> minDataList = minDataVO.getData();
//        log.info("minDataList size = {}" , minDataList.size());

        double[][] values = null;
        Object[][] volumes = null;
        String[] date = null;

        if(minDataList.size() > 0){
            //  初始化 values
            values = new double[minDataList.size()][5];
            //  初始化 volumes
            volumes = new Object[minDataList.size()][3];
            //  初始化 date
            date = new String[minDataList.size()];

            for (int i = 0; i < minDataList.size(); i++){
                SinaStockMinData sinaStockMinData = minDataList.get(i);

                for (int j = 0; j < values[i].length; j++){
                    values[i][0] = Double.valueOf(sinaStockMinData.getOpen());
                    values[i][1] = Double.valueOf(sinaStockMinData.getClose());
                    values[i][2] = Double.valueOf(sinaStockMinData.getLow());
                    values[i][3] = Double.valueOf(sinaStockMinData.getHigh());
                    values[i][4] = Double.valueOf(sinaStockMinData.getVolume());
                }
                for (int k = 0; k < volumes[i].length; k++){
                    volumes[i][0] = i;
                    volumes[i][1] = Double.valueOf(sinaStockMinData.getVolume());
                    //  如果 ma_volume5 - high 大于 0 就红色，反之绿色
                    if(new BigDecimal(sinaStockMinData.getClose())
                            .compareTo(new BigDecimal(sinaStockMinData.getOpen())) == 1){
                        volumes[i][2] = 1;
                    }else{
                        volumes[i][2] = -1;
                    }
                }

                date[i] = sinaStockMinData.getDay();
            }
        }

        echartsDataVO.setValues(values);
        echartsDataVO.setVolumes(volumes);
        echartsDataVO.setDate(date);

        return echartsDataVO;
    }

    //  var hq_str_sh601318="�й�ƽ��,67.500,67.200,68.500,69.100,67.440,68.490,68.500,73952387,5052835863.000,1500,68.490,1000,68.480,2900,68.470,4400,68.460,34500,68.450,147468,68.500,4700,68.510,2000,68.520,500,68.530,400,68.540,2018-09-28,15:00:00,00";
    public static void main(String[] args) {
        List list = Lists.newArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        System.out.println(list.size());

        String[][] values = new String[list.size()][5];

        System.out.println("[]" + values.length);
        System.out.println("[][]" + values[1].length);

        System.out.println(SinaStockApi.getSinaStock("sh601318"));

        String sss = "[\n" +
                "{\n" +
                "\"day\": \"2019-03-05 14:50:00\",\n" +
                "\"open\": \"13.020\",\n" +
                "\"high\": \"13.040\",\n" +
                "\"low\": \"13.000\",\n" +
                "\"close\": \"13.040\",\n" +
                "\"volume\": \"2611513\",\n" +
                "\"ma_price5\": 13.01,\n" +
                "\"ma_volume5\": 3216535\n" +
                "},\n" +
                "{\n" +
                "\"day\": \"2019-03-05 14:55:00\",\n" +
                "\"open\": \"13.040\",\n" +
                "\"high\": \"13.040\",\n" +
                "\"low\": \"13.010\",\n" +
                "\"close\": \"13.030\",\n" +
                "\"volume\": \"2296000\",\n" +
                "\"ma_price5\": 13.016,\n" +
                "\"ma_volume5\": 3044839\n" +
                "}\n" +
                "]";

//        {day:"2019-03-05 14:55:00",open:"13.040",high:"13.040",low:"13.010",close:"13.040",volume:"2773000",ma_price5:13.018,ma_volume5:3140239

        sss = sss.substring(1,sss.length() - 1);

        sss = "{" + sss + "}" ;


//        List<String> list = sss.



    }



}
